const secrect = "wuxiaotian";
const cookiekey = 'token';
const jwt = require('jsonwebtoken');
// 颁发jwt
exports.publish = function(res,maxage = 3600*20,info = {}){
    const token =  jwt.sign(info,secrect,{
        expiresIn:maxage
    })

    // 添加到cookie
    // res.cookie(cookiekey,token,{
    //     maxage:maxage,
    //     path:'/'
    // });
    // 添加其他设备的验证
    // res.header('authorization',token);
    return token;
}

// 验证jwt
exports.verify = function(req,res){
    let token = '';
    token = req.cookies[cookiekey];
    if (!token) {
        token =  req.headers.authorization;
        if (!token) {
            return null;
        }
        token = token.split(" ");
        token = token.length === 1?token[0]:token[1];
        try{
            const result = jwt.verify(token,secrect);
            return result;
        }catch{
            return null;
        }
        
    }
}